//
//  CZStatusPictureView.swift
//  Weibo30
//
//  Created by apple on 16/8/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

//  重用标记
private let StatusPictureViewCellIdentifier = "StatusPictureViewCellIdentifier"
//  每项之间间距
private let itemMargin: CGFloat = 5
//  每项的宽度
private let itemWidth = (ScreenWidth - 2 * StatusTableViewCellMargin - 2 * itemMargin) / 3

//  微博配图视图
class CZStatusPictureView: UICollectionView {
    //  显示配图的数据源
    var picUrls: [CZStatusPictureInfo]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            
            //  根据配图的个数计算大小
            let size = calcSizeWithCount(picUrls?.count ?? 0)
            //  更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            
            
            //  绑定数据
            self.reloadData()
            
        }
    }
    
    //  显示配图个数
    private lazy var messageLabel: UILabel = UILabel(fontSize: 20, textColor: UIColor.whiteColor())
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        
        //  注册cell
        registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellIdentifier)
        //  设置数据代理
        dataSource = self
        //  设置代理
        delegate = self
        
        addSubview(messageLabel)
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        
    }
    
    //  通过配图的个数计算配图的大小
    private func calcSizeWithCount(count: Int) -> CGSize {
       
        
        //  列数怎么计算
        //  列数
        let cols = count > 3 ? 3 : count
        //  行数
        let rows = (count - 1) / 3 + 1
        
        
        //  计算配图的大小
        //  宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //  高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
    
        return CGSize(width: currentWidth, height: currentHeight)
        
    }
    

}

//  MARK:   - 实现UICollectionViewDataSource的协议
extension CZStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellIdentifier, forIndexPath: indexPath) as! CZStatusPictureViewCell
        //  设置模型数据
        cell.picInfo = picUrls![indexPath.item]

        return cell
        
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
//        photoBrowser.delegate = self;
//        photoBrowser.currentImageIndex = indexPath.item;
//        photoBrowser.imageCount = self.modelsArray.count;
//        photoBrowser.sourceImagesContainerView = self.collectionView;
//        
//        [photoBrowser show];
        
         let photoBrowser = SDPhotoBrowser()
         photoBrowser.delegate = self
         photoBrowser.currentImageIndex = indexPath.item
         photoBrowser.imageCount = picUrls!.count
         photoBrowser.sourceImagesContainerView = self
         photoBrowser.show()
        
        
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
//        SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
//        
//        return cell.imageView.image;
        
        
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath) as! CZStatusPictureViewCell
        return cell.imageView.image
        
        
        
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
//        NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
//        return [NSURL URLWithString:urlStr];
        
        let urlStr = picUrls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
        
    }
    
    
}


//  自定义配图cell
class CZStatusPictureViewCell: UICollectionViewCell {
 
    //  绑定数据
    var picInfo: CZStatusPictureInfo? {
        didSet {
            if let url = picInfo?.thumbnail_pic {
                imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
//                if url.hasSuffix(".gif") {
//                    gifImageView.hidden = false
//                } else {
//                    gifImageView.hidden = true
//                }
                
                //  判断gif图片是否显示
                gifImageView.hidden = !url.hasSuffix(".gif")
                
                
                
            }
        }
    }
    
    //  MARK:   --懒加载控件
    private lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  修改显示模型为等比填充,保证图片比例不变
        view.contentMode = UIViewContentMode.ScaleAspectFill
        //  多余图片剪切掉
        view.clipsToBounds = true
        return view
    
    }()
    //  gif图片视图
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        //  添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        //  设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
    }
    
}




















